package com.dili.dd.flume.plugin.exthdfs;

import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * Created by zhaoYuan on 2015/4/13.
 */
public class DateUtil {

    private DateTimeFieldType timeUnit;


    public DateUtil(DateTimeFieldTypeEnum timeUnit) throws NoSuchFieldException, IllegalAccessException {
        this.timeUnit = (DateTimeFieldType) ReflectUtils.getValueByFieldName(DateTimeFieldType.class, timeUnit.name());
    }

    public DateTime getCurrentNatureTime(DateTime dateTime ) {
        return dateTime.property(timeUnit).roundCeilingCopy();
    }

    public DateTime getNextNatureTime(DateTime dateTime) {
        return dateTime.property(timeUnit).roundCeilingCopy();
    }

    /**
     * 获取到下一个时间单位的毫秒数
     * @return
     */
    public long getMillisecond2NextNatureTime(DateTime time){
        return getNextNatureTime(time).getMillis() - time.getMillis();
    }


    public long getMillisecond2NextNatureTime(){
        return getMillisecond2NextNatureTime(DateTime.now());
    }

    /**
     * 初始化时间单位的缓存
     *
     * @return
     */
    private List<String> getAvailableTypes() throws IllegalAccessException {

        Class<DateTimeFieldType> clazz = DateTimeFieldType.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        List<String> types = new LinkedList<String>();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            int modifiers = field.getModifiers();
            if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) && field.getType().equals(clazz)) {
                boolean accessible = field.isAccessible();
                if (!accessible) field.setAccessible(true);
                DateTimeFieldType o = (DateTimeFieldType) field.get(null);
                if (!accessible) field.setAccessible(accessible);
                String name = field.getName();
//                typeCache.put(name, o);
                types.add(name);
            }
        }
        return types;
    }
}
